package com.io.stream.ionew;

import com.io.stream.IoParam;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class IoNew01 {
    public static void main(String[] args) throws Exception {
        // 源文件 目标文件
        File source = new File(IoParam.BASE_PATH+"fileio-02.png") ;
        File target = new File(IoParam.BASE_PATH+"channel-"+source.getName()) ;

        // 输入字节流通道
        FileInputStream inStream = new FileInputStream(source);
        FileChannel inChannel = inStream.getChannel();

        // 输出字节流通道
        FileOutputStream outStream = new FileOutputStream(target);
        FileChannel outChannel = outStream.getChannel();

        // 直接通道复制
        // outChannel.transferFrom(inChannel, 0, inChannel.size());

        // 缓冲区读写机制
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        while (true) {
            // 读取通道中数据到缓冲区
            int in = inChannel.read(buffer);
            if (in == -1) {
                break;
            }
            // 读写切换
            buffer.flip();
            // 写出缓冲区数据
            outChannel.write(buffer);
            // 清空缓冲区
            buffer.clear();
        }
        outChannel.close();
        inChannel.close();
    }
}
